package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.RoleDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Role;
import com.itheima.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap;
import java.util.List;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {
    @Autowired
    RoleDao roleDao;

    @Override
    public void add(Role role, Integer[] menuIds, Integer[] permissionIds) {
        roleDao.add(role);
        addRoleAndMenu(role.getId(),menuIds);
        addRoleAndPermission(role.getId(),permissionIds);
    }

    @Override
    public void del(Integer[] ids) {
        for (Integer id : ids) {
            roleDao.delMenuByRoleId(id);
            roleDao.delPermissionByRoleId(id);
            roleDao.del(id);
        }
    }

    @Override
    public void update(Role role,Integer[] menuIds, Integer[] permissionIds) {
        roleDao.delMenuByRoleId(role.getId());
        roleDao.delPermissionByRoleId(role.getId());
        roleDao.update(role);
        addRoleAndMenu(role.getId(),menuIds);
        addRoleAndPermission(role.getId(),permissionIds);
    }

    @Override
    public Role find(Integer id) {
        return roleDao.find(id);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Role> roles= roleDao.findPage(queryPageBean.getQueryString());
        return new PageResult(roles.getTotal(),roles);
    }

    @Override
    public List<Role> findAll() {
        return  roleDao.findAll();
    }

    @Override
    public List<Integer> findRolesIdsByUserId(Integer id) {
        List<Integer> roleIds = roleDao.findRoleIdsByUserId(id);

        return roleIds;
    }

    private void addRoleAndMenu(Integer roleId,Integer[] menuIds){
        HashMap<String, Integer> menuMap = new HashMap<>();
        for (Integer menuId : menuIds) {
            menuMap.put("roleId",roleId);
            menuMap.put("menuId",menuId);
            roleDao.addRoleAndMenu(menuMap);
        }
    }

    private void addRoleAndPermission(Integer roleId,Integer[] permissionIds){
        HashMap<String, Integer> permissionMap = new HashMap<>();
        for (Integer permissionId : permissionIds) {
            permissionMap.put("roleId",roleId);
            permissionMap.put("permissionId",permissionId);
            roleDao.addRoleAndPermission(permissionMap);
        }
    }
}
